package com.zshan.clinic.cms.framework.config.druid;

import com.alibaba.druid.pool.DruidDataSource;
import com.zshan.clinic.mybatis.SuperMapper;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import java.sql.SQLException;

@Configuration
@EnableTransactionManagement(proxyTargetClass = true)//启注解事务管理，等同于xml配置方式的 <tx:annotation-driven />
@EnableAspectJAutoProxy(exposeProxy = true) //同类中使用切面类调用其他方法
@MapperScan(basePackages = {"com.zshan.clinic.database.dao","com.zshan.clinic.admin.mapper"}, markerInterface = SuperMapper.class, sqlSessionFactoryRef = "clinicSqlSessionFactory")
public class ClinicDataSourceConfiguration extends AbstractDruidDBConfig {

    @Value("${spring.datasource.clinic.url}")
    private String url;

    @Value("${spring.datasource.clinic.username}")
    private String username;

    @Value("${spring.datasource.clinic.password}")
    private String password;

    @Value("${spring.datasource.clinic.mapperLocations}")
    private String [] mapperLocations;


    // 注册 bookDataSource
    @Bean(name = "clinicDataSource", initMethod = "init", destroyMethod = "close")
    public DruidDataSource dataSource() {
        return super.createDataSource(url, username, password);
    }

    @Bean(name = "clinicSqlSessionFactory")
    public SqlSessionFactory sqlSessionFactory() throws Exception {
        return super.sqlSessionFactory(dataSource(),mapperLocations,null);
    }

    @Bean(name = "clinicTransactionManager")
    public PlatformTransactionManager clinicTransactionManager() throws SQLException {
        return new DataSourceTransactionManager(dataSource());
    }
}
